package com.gjy.quartz.cluster;

import com.gjy.quartz.trigger.TriggerJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-30 16:28:34
 */
public class ClusterJobTest {
    private static final Logger log = LoggerFactory.getLogger(ClusterJobTest.class);

    public static void main(String[] args) throws Exception {
        // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        StdSchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
        scheduler.start();

        defineJob(scheduler);

        log.info("instanceId: {}", scheduler.getSchedulerInstanceId());
        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }

    private static void defineJob(Scheduler scheduler) throws Exception {
        JobKey jobKey = new JobKey("c2", "c2");
        if (scheduler.checkExists(jobKey)) {
            log.info("任务已存在: {}", jobKey);
            return;
        }

        JobDetail job = JobBuilder.newJob(TriggerJob.class)
                .withIdentity(jobKey)
                .storeDurably()
                .usingJobData("name", "hello")
                .usingJobData("time", LocalDateTime.now().toString())
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(new TriggerKey("clusterTrigger2", "clusterTrigger2"))
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(15).repeatForever())
                .build();
        scheduler.scheduleJob(job, trigger);
    }
}
